<template>
  <!--面包屑导航-->
  <el-row style="margin: 5px 5px;">
    <el-col :span="24">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>主数据</el-breadcrumb-item>
        <el-breadcrumb-item>物料产品管理</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>
  <!--查询条件区-->
  <el-row>
    <el-col :span="24">
      <el-form :model="searchItem" inline>
        <el-form-item label="物料编码">
          <el-input v-model="searchItem.itemCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="searchItem.itemName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item>
          <el-button @click="fetchItemList(searchItem)" type="primary">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
  <!--按钮功能区-->
  <el-row style="margin: 5px 5px;">
    <el-col :span="24">
      <el-button-group>
        <el-button @click="insert" type="primary">
          新增
        </el-button>
        <el-button @click="updateTool" type="success">
          修改
        </el-button>
        <el-button @click="deleteDevList" type="danger" :disabled="selectedItems.length === 0">
          删除
        </el-button>
      </el-button-group>
    </el-col>
  </el-row>

  <el-row>
    <el-col :span="24">
      <el-table :data="pagedData" border stripe style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="itemCode" label="物料编码" width="150">
          <template #default="scope">
            <el-link @click="itemDetails(scope.row)" type="primary">{{ scope.row.itemCode }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="itemName" label="物料名称" width="150"></el-table-column>
        <el-table-column prop="specification" label="物料规格" width="150"></el-table-column>
        <el-table-column prop="unitName" label="单位" width="150"></el-table-column>
        <el-table-column prop="itemOrProduct" label="物料/产品" width="150"></el-table-column>
        <el-table-column prop="itemTypeName" label="所属分类" width="150"></el-table-column>
        <el-table-column prop="enableFlag" label="是否启用" width="120">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enableFlag == 'Y'">是</el-tag>
            <el-tag type="danger" v-else-if="scope.row.enableFlag == 'N'">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="safeStockFlag" label="设置安全库存" width="120">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.safeStockFlag == 'Y' ">是</el-tag>
            <el-tag type="danger" v-else-if="scope.row.safeStockFlag == 'N'">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          style="margin-top: 20px"
          background
          layout="prev, pager, next, total"
          :total="total"
          :page-size="pageSize"
          @current-change="handlePageChange"
      />
    </el-col>
  </el-row>

<!--  新增弹窗-->
  <el-row>
    <div>
      <el-dialog v-bind="$attrs" title="新增物料/产品" v-model="dialogInsertVisiable">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-form-item label="物料编码" prop="itemCode">
            <el-input v-model="formData.itemCode" placeholder="请输入物料编码" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="物料名称" prop="itemName">
            <el-input v-model="formData.itemName" placeholder="请输入物料名称" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="规格型号" prop="specification">
            <el-input v-model="formData.specification" type="textarea" placeholder="请输入规格型号"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="unitName">
            <el-select v-model="formData.unitName" placeholder="请选择单位" clearable :style="{width: '100%'}">
              <el-option
              v-for="unit in unitList"
              :key="unit.unitId"
              :label="unit.unitName"
              :value="unit.unitName"
              >

              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物料产品分类" prop="itemTypeName">
            <el-select v-model="formData.itemTypeName" placeholder="请选择所属分类" clearable :style="{width: '100%'}">
              <el-option
              v-for="itemType in itemTypeList"
              :key="itemType.itemTypeId"
              :label="itemType.itemTypeName"
              :value="itemType.itemTypeName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用" prop="enableFlag">
            <el-radio-group v-model="formData.enableFlag">
              <el-radio :value = "'Y'" label="是"/>
              <el-radio :value = "'N'" label="否"/>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="安全库存" prop="safeStockFlag">
            <el-radio-group v-model="formData.safeStockFlag" size="medium">
              <el-radio-group v-model="formData.safeStockFlag">
                <el-radio :value = "'Y'" label="是"/>
                <el-radio :value = "'N'" label="否"/>
              </el-radio-group>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="最小库存量" v-if="formData.safeStockFlag == 'Y'">
            <el-input-number v-model="formData.minStock" placeholder="计数器"></el-input-number>
          </el-form-item>
          <el-form-item label="最大库存量" v-if="formData.safeStockFlag == 'Y'">
            <el-input-number v-model="formData.maxStock" placeholder="计数器"></el-input-number>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </el-row>

<!--  修改弹窗-->
  <el-row>
    <div>
      <el-dialog v-bind="$attrs" title="修改物料/产品" v-model="dialogUpdateVisiable" >
        <el-form ref="elForm" :model="updateFormData" :rules="rules" size="medium" label-width="100px">
          <el-form-item label="物料编码" prop="itemCode">
            <el-input v-model="updateFormData.itemCode" placeholder="请输入物料编码" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="物料名称" prop="itemName">
            <el-input v-model="updateFormData.itemName" placeholder="请输入物料名称" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="规格型号" prop="specification">
            <el-input v-model="updateFormData.specification" type="textarea" placeholder="请输入规格型号"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="unitName">
            <el-select v-model="updateFormData.unitName" placeholder="请选择单位" clearable :style="{width: '100%'}">
              <el-option
                  v-for="unit in unitList"
                  :key="unit.unitId"
                  :label="unit.unitName"
                  :value="unit.unitId"
              >

              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物料产品分类" prop="itemTypeName">
            <el-select v-model="updateFormData.itemTypeName" placeholder="请选择所属分类" clearable :style="{width: '100%'}">
              <el-option
                  v-for="itemType in itemTypeList"
                  :key="itemType.itemTypeId"
                  :label="itemType.itemTypeName"
                  :value="itemType.itemTypeId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用" prop="enableFlag">
            <el-radio-group v-model="updateFormData.enableFlag">
              <el-radio :value = "'Y'" label="是"/>
              <el-radio :value = "'N'" label="否"/>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="安全库存" prop="safeStockFlag">
            <el-radio-group v-model="updateFormData.safeStockFlag" size="medium">
              <el-radio-group v-model="updateFormData.safeStockFlag">
                <el-radio :value = "'Y'" label="是"/>
                <el-radio :value = "'N'" label="否"/>
              </el-radio-group>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="updateFormData.remark" type="textarea" placeholder="请输入备注"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-form>
        <el-tabs type="border-card">
          <el-tab-pane label="Bom组成">
            <!--按钮功能区-->
            <el-row style="margin: 5px 5px;">
              <el-col :span="24">
                <el-button-group>
                  <el-button @click="itemBomInsert" type="primary">
                    新增
                  </el-button>
                  <el-button @click="deleteDevList" type="danger" :disabled="selectedItems.length === 0">
                    删除
                  </el-button>
                </el-button-group>
              </el-col>
            </el-row>
            <el-table :data="itemBomList"
                      @selection-change="">
              <el-table-column type="selection" width="55" align="center"></el-table-column>
              <el-table-column prop="bomItemCode" label="物料编码" width="150"></el-table-column>
              <el-table-column prop="bomItemName" label="物料名称" width="150"></el-table-column>
              <el-table-column prop="bomItemSpec" label="规格" width="150"></el-table-column>
              <el-table-column prop="unitOfMeasure" label="单位" width="150"></el-table-column>
              <el-table-column prop="quantity" label="使用比例" width="150"></el-table-column>
              <el-table-column width="150" label="操作">
                <template #default="scope">
                  <el-button type="primary" @click="itemBomEdit(scope.row.bomId)" ><el-icon><Edit /></el-icon></el-button>
                  <el-button type="danger"  @click="itemBomDel(scope.row.bomId)"><el-icon><Delete /></el-icon></el-button>
                </template>
              </el-table-column>
            </el-table>

          </el-tab-pane>
          <el-tab-pane label="供应商">Config</el-tab-pane>
          <el-tab-pane label="替代品">Role</el-tab-pane>
          <el-tab-pane label="SIP">

              <template #default="scope">
                <el-button type="primary" @click="addSip()"><el-icon class="el-icon-plus">
                  <Plus />
                </el-icon>新增</el-button>
              </template>

          </el-tab-pane>
          <el-tab-pane label="SOP">
            <el-button type="primary" @click="addSop()"><el-icon class="el-icon-plus">
              <Plus />
            </el-icon>新增</el-button>
          </el-tab-pane>
        </el-tabs>
        <div slot="footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="handleUpdataConfirm">确定</el-button>
        </div>
      </el-dialog>
    </div>

  </el-row>
  <!-- 显示原图的弹出框 -->
  <el-dialog v-model="dialogSipPicVisible" width="50%">
    <img :src="imageUrl" style="width: 100%;" />
  </el-dialog>
  <!-- 显示原图的弹出框 -->
  <el-dialog v-model="dialogSopPicVisible" width="50%">
    <img :src="imageUrl" style="width: 100%;" />
  </el-dialog>
<!--  详情弹窗-->
  <el-row>
    <div>
      <el-dialog v-bind="$attrs" title="查看物料/产品" v-model="dialogDetailVisiable" >
        <el-form ref="elForm" :model="updateFormData" size="small" label-width="100px" disabled="true">
          <el-form-item label="物料编码" prop="itemCode">
            <el-input v-model="updateFormData.itemCode" placeholder="请输入物料编码" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="物料名称" prop="itemName">
            <el-input v-model="updateFormData.itemName" placeholder="请输入物料名称" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="规格型号" prop="specification">
            <el-input v-model="updateFormData.specification" type="textarea" placeholder="请输入规格型号"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="unitName" >
            <el-select v-model="updateFormData.unitName" placeholder="请选择单位" clearable :style="{width: '100%'}">
              <el-option
                  v-for="unit in unitList"
                  :key="unit.unitId"
                  :label="unit.unitName"
                  :value="unit.unitId"
              >

              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物料产品分类" prop="itemTypeName">
            <el-select v-model="updateFormData.itemTypeName" placeholder="请选择所属分类" clearable :style="{width: '100%'}">
              <el-option
                  v-for="itemType in itemTypeList"
                  :key="itemType.itemTypeId"
                  :label="itemType.itemTypeName"
                  :value="itemType.itemTypeId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用" prop="enableFlag">
            <el-radio-group v-model="updateFormData.enableFlag">
              <el-radio :value = "'Y'" label="是"/>
              <el-radio :value = "'N'" label="否"/>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="安全库存" prop="safeStockFlag">
            <el-radio-group v-model="updateFormData.safeStockFlag" size="medium">
              <el-radio-group v-model="updateFormData.safeStockFlag">
                <el-radio :value = "'Y'" label="是"/>
                <el-radio :value = "'N'" label="否"/>
              </el-radio-group>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="updateFormData.remark" type="textarea" placeholder="请输入备注"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-form>

          <el-tabs type="border-card">
            <el-tab-pane label="Bom组成">
              <el-table :data="itemBomList">
                  <el-table-column type="selection" width="55" align="center"></el-table-column>
                  <el-table-column prop="bomItemCode" label="物料编码" width="150"></el-table-column>
                  <el-table-column prop="bomItemName" label="物料名称" width="150"></el-table-column>
                  <el-table-column prop="bomItemSpec" label="规格" width="150"></el-table-column>
                  <el-table-column prop="unitOfMeasure" label="单位" width="150"></el-table-column>
                  <el-table-column prop="quantity" label="使用比例" width="150"></el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="供应商">Config</el-tab-pane>
            <el-tab-pane label="替代品">Role</el-tab-pane>
            <el-tab-pane label="SIP">
              <el-row>
                <el-card
                    v-for="(item, index) in itemSipList"
                    :key="index"
                    style="max-width: 150px;margin: 10px "  shadow="always" :data="itemSipList">
                  <template #header>{{ item.sipTitle }}</template>
                  <el-image style="width: 100px; height: 100px"
                            :src="item.sipUrl"
                            @click="sipDetail(item.sipId)"
                  ></el-image>
                </el-card>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="SOP">
              <el-row>
                <el-card
                    v-for="(item, index) in itemSopList"
                    :key="index"
                    style="max-width: 150px;margin: 10px "  shadow="always" :data="itemSopList">
                  <template #header>{{ item.sopTitle }}</template>
                  <el-image style="width: 100px; height: 100px"
                            :src="item.sopUrl"
                            @click="sopDetail(item.sopId)"
                  ></el-image>
                </el-card>
              </el-row>
            </el-tab-pane>
          </el-tabs>


        <div slot="footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="handleUpdataConfirm">确定</el-button>
        </div>
      </el-dialog>
    </div>

  </el-row>

<!--  物料产品选择弹窗-->
  <el-dialog title="物料产品选择" v-model="dialogSelectVisiable" width="100%" align-center>
    <el-table :data="pagedData" border stripe style="width: 100%" @selection-change="handleItemBomSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="itemCode" label="物料编码" width="150"></el-table-column>
      <el-table-column prop="itemName" label="物料名称" width="150"></el-table-column>
      <el-table-column prop="specification" label="物料规格" width="150"></el-table-column>
      <el-table-column prop="unitName" label="单位" width="150"></el-table-column>
      <el-table-column prop="itemOrProduct" label="物料/产品" width="150"></el-table-column>
      <el-table-column prop="itemTypeName" label="所属分类" width="150"></el-table-column>

    </el-table>
    <!-- 分页组件 -->
    <el-pagination
        style="margin-top: 20px"
        background
        layout="prev, pager, next, total"
        :total="total"
        :page-size="pageSize"
        @current-change="handlePageChange"
    />
    <div slot="footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="handleItemBomAddSelectConfirm">确定</el-button>
    </div>
  </el-dialog>

  <el-dialog title="修改产品BOM关系" v-model="dialogItemBomEditVisible" width="60%" align-center>
    <el-form :model="updateBomFormData" label-width="100px" >
      <el-form-item label="BOM物料编码" >
        <el-input v-model="updateBomFormData.bomItemCode" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="BOM物料名称" >
        <el-input v-model="updateBomFormData.bomItemName" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="BOM物料规格" >
        <el-input  type="textarea" v-model="updateBomFormData.bomItemSpec" clearable :style="{width: '100%'}" :autosize="{minRows: 4, maxRows: 4}">
        </el-input>
      </el-form-item>
      <el-form-item label="BOM物料单位" >
        <el-input v-model="updateBomFormData.unitOfMeasure" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="计数器" prop="quantity">
        <el-input-number v-model="updateBomFormData.quantity" placeholder="计数器" :precision='4'></el-input-number>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="handleItemBomEditSelectConfirm">确定</el-button>
    </div>
  </el-dialog>


  <el-dialog title="SIP详情" v-model="dialogSipDetailVisiable" width="60%" align-center>
    <el-form :model="itemSipDetail" label-width="100px">
      <el-form-item label="工序" prop="sipTitle">
        <el-input v-model="itemSipDetail.sipTitle" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="名称" prop="sipTitle">
        <el-input v-model="itemSipDetail.processName" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="描述" prop="sipTitle">
        <el-input v-model="itemSipDetail.sipDescription" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="图片" prop="sipUrl">
        <el-image style="width: 200px; height: 200px"
                  :src="itemSipDetail.sipUrl"
        ></el-image>
      </el-form-item>

    </el-form>
  </el-dialog>

  <el-dialog title="SOP详情" v-model="dialogSopDetailVisiable" width="60%" align-center>
    <el-form :model="itemSopDetail" label-width="100px">
      <el-form-item label="工序" prop="sopTitle">
        <el-input v-model="itemSopDetail.sopTitle" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="名称" prop="sopTitle">
        <el-input v-model="itemSopDetail.processName" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="描述" prop="sopTitle">
        <el-input v-model="itemSopDetail.sopDescription" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="图片" prop="sopUrl">
        <el-image style="width: 200px; height: 200px"
                  :src="itemSopDetail.sopUrl"
        ></el-image>
      </el-form-item>

    </el-form>
  </el-dialog>

  <el-dialog title="新增sip" v-model="dialogSipAddVisible" width="60%" align-center>
    <el-form :model="itemSipAddFormData" label-width="100px">
      <el-form-item label="标题" prop="sipTitle">
        <el-input v-model="itemSipAddFormData.sipTitle" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="展示顺序" prop="field101">
        <el-input-number v-model="itemSipAddFormData.orderNum" ></el-input-number>
      </el-form-item>
      <el-form-item label="详细描述" prop="field102">
        <el-input v-model="itemSipAddFormData.sipDescription" type="textarea" placeholder="请输入详细描述"
                  :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
      </el-form-item>
      <el-form-item label="所属工艺" prop="processId">
        <el-select v-model="itemSipAddFormData.processId" placeholder="请选择所属工艺">
          <el-option v-for="item in proProcess" :key="item.processId" :label="item.processName" :value="item.processId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图片" prop="sipUrl">
        <div class="upload-container">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8060/oss/showImg"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
          >
            <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
                @click="showOriginalImage"
            />
            <el-icon v-else class="el-icon-plus avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
      </el-form-item>

    </el-form>
    <div slot="footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="handleSipAddConfirm">确定</el-button>
    </div>
  </el-dialog>

  <el-dialog title="新增sop" v-model="dialogSopAddVisible" width="60%" align-center>
    <el-form :model="itemSopAddFormData" label-width="100px">
      <el-form-item label="标题" prop="sopTitle">
        <el-input v-model="itemSopAddFormData.sopTitle" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="展示顺序" prop="field101">
        <el-input-number v-model="itemSopAddFormData.orderNum" ></el-input-number>
      </el-form-item>
      <el-form-item label="详细描述" prop="field102">
        <el-input v-model="itemSopAddFormData.sopDescription" type="textarea" placeholder="请输入详细描述"
                  :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
      </el-form-item>
      <el-form-item label="所属工艺" prop="processId">
        <el-select v-model="itemSopAddFormData.processId" placeholder="请选择所属工艺">
          <el-option v-for="item in proProcess" :key="item.processId" :label="item.processName" :value="item.processId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图片" prop="sopUrl">
        <div class="upload-container">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8060/oss/showImg"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
          >
            <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
                @click="showOriginalImage"
            />
            <el-icon v-else class="el-icon-plus avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
      </el-form-item>

    </el-form>
    <div slot="footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="handleSopAddConfirm">确定</el-button>
    </div>
  </el-dialog>
</template>




<script setup>

import {searchItem, handlePageChange, pagedData, pageSize, total, fetchItemList, itemList} from "@/api/md/item/itemLogic.js";
import {onMounted, ref} from "vue";
import itemRequest from "@/api/md/item/item.js";
import unitRequest from "@/api/md/unit/unit.js";
import itemTypeRequest from "@/api/md/item/itemType.js";
import {ElMessage, ElMessageBox} from "element-plus";
import ItemDialog from "@/views/mainData/item/itemDialog.vue";
import item from "@/api/md/item/item.js";

//初始化formData
const formData = ref({
  itemCode: "",
  itemName: "",
  specification: "",
  unitName: "",
  itemTypeName: "",
  itemTypeId: "",
  itemTypeCode: "",
  itemOrProduct: "",
  enableFlag: "",
  safeStockFlag: "",
  minStock: "",
  maxStock: "",
  remark: "",
  unitOfMeasure: "",
  itemStatus: 1
});
const updateFormData = ref({});
const updateBomFormData = ref({});//修改bom表单存储的数据
const delBomTemp = ref({});//删除表所存储的数据
const searchUnit = ref({});
const searchItemType = ref({});
const dialogInsertVisiable = ref(false);
const unitList = ref([]);  // 全部数据
const itemTypeList = ref([]);  // 全部数据
const dialogUpdateVisiable = ref(false);
const dialogDetailVisiable = ref(false);//详情页
const dialogSelectVisiable = ref(false);
const dialogItemBomEditVisible = ref(false);
const dialogSipPicVisible = ref(false);
const dialogSipDetailVisiable = ref(false);
const dialogSipAddVisible = ref(false);//sip新增页面
const dialogSopPicVisible = ref(false);
const dialogSopDetailVisiable = ref(false);
const dialogSopAddVisible = ref(false);//sop新增页面
// 存储选中的行
const selectedItems = ref([]);
const selectedItemBoms = ref([]);
const itemBomList = ref([]);//bom列表
const itemSipList = ref([]);//sip列表
const itemSopList = ref([])//sop列表
const proProcess = ref([]);//process列表
const itemSipDetail = ref({})
const itemSipAddFormData = ref({})
const itemSopDetail = ref({})
const itemSopAddFormData = ref({})
const tempItemId = ref(null);
const imageUrl = ref('');//上传成功之后的图片地址
//上传图片的请求头
let headers = ref({token:localStorage.getItem("token")})

function handleSipAddConfirm(){
  itemSipAddFormData.value.processCode = proProcess.value[itemSipAddFormData.value.processId].processCode
  itemSipAddFormData.value.processName = proProcess.value[itemSipAddFormData.value.processId].processName
  console.log(itemSipAddFormData.value)
  itemRequest.addSip(itemSipAddFormData.value,(data) => {
    ElMessage({
      type: "success",
      message: "新增成功"
    })
    dialogSipAddVisible.value = false
  })
}
function handleSopAddConfirm(){
  itemSopAddFormData.value.processCode = proProcess.value[itemSopAddFormData.value.processId].processCode
  itemSopAddFormData.value.processName = proProcess.value[itemSopAddFormData.value.processId].processName
  console.log(itemSopAddFormData.value)
  itemRequest.addSop(itemSopAddFormData.value,(data) => {
    ElMessage({
      type: "success",
      message: "新增成功"
    })
    dialogSopAddVisible.value = false
  })
}

function addSip(itemId){
  //将itemId赋值给itemSipAddFormData
  itemSipAddFormData.value.itemId = tempItemId.value
  console.log(itemSipAddFormData.value)
  //请求所有工序列表
  itemRequest.queryProcessList(itemId,(data) => {
    proProcess.value = data.data

  })
  dialogSipAddVisible.value = true
}

function addSop(itemId){
  //将itemId赋值给itemSopAddFormData
  itemSopAddFormData.value.itemId = tempItemId.value
  console.log(itemSopAddFormData.value)
  //请求所有工序列表
  itemRequest.queryProcessList(itemId,(data) => {
    proProcess.value = data.data

  })
  dialogSopAddVisible.value = true
}

function sipDetail(sipId){  //显示sip的详情
  itemRequest.querySipById(sipId, (data) => {
    itemSipDetail.value = data.data
    dialogSipDetailVisiable.value = true
  })
}
function sopDetail(sopId){  //显示sop的详情
  itemRequest.querySopById(sopId, (data) => {
    itemSopDetail.value = data.data
    dialogSopDetailVisiable.value = true
  })
}

// 上传成功的处理
function handleUploadSuccess(response, file) {
  ElMessage.success('上传成功');
  imageUrl.value = URL.createObjectURL(file.raw); // 使用上传的文件生成图片URL展示
  console.log(imageUrl.value)
  itemSipAddFormData.value.sipUrl = imageUrl.value
  itemSopAddFormData.value.sopUrl = imageUrl.value

}

// 上传失败的处理
function handleUploadError(error) {
  ElMessage.error('上传失败，请重试');
}

// 上传前检查文件格式和大小
function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
}
// 点击缩略图显示原图
function showOriginalImage() {
  dialogSipPicVisible.value = true;
  dialogSopPicVisible.value = true;
}

//bom修改提交按钮
function handleItemBomEditSelectConfirm(){
  itemRequest.itemBomEditDateSubmit(updateBomFormData.value, (data) => {
    console.log("修改结果: ", data)
    if (data.msg == "OK"){
      ElMessage({
        type: "success",
        message: "修改成功"
      });
      // 重新加载数据
      fetchItemList(searchItem);
    }
  })
}

//bom单个删除按钮
function itemBomDel(bomId){
  ElMessageBox.confirm('确定要删除该BOM吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    console.log("删除数据: ", bomId)
    itemRequest.selectItemBomById(bomId, (data) =>{
      updateBomFormData.value = data.data;
      updateBomFormData.value.bomItemStatus = 99;
      delBomTemp.value = updateBomFormData.value;
      console.log("删除数据: ", delBomTemp.value)
      itemRequest.itemBomEditDateSubmit(delBomTemp.value, (data) => {
        console.log("删除结果: ", data)
        if (data.msg == "OK"){
          ElMessage({
            type: "success",
          })
        }
      })
    })
    console.log("删除数据: ", delBomTemp.value)


  })
}

//bom单个修改按钮
function itemBomEdit(bomId){
  itemRequest.selectItemBomById(bomId, (data) => {
    updateBomFormData.value = data.data;
    console.log(updateBomFormData.value)
    dialogItemBomEditVisible.value = true;
  })
}

function handleItemBomSelectionChange(val){
  selectedItemBoms.value = val;
}

function handleItemBomAddSelectConfirm(){
  //提交前将itemBomList中的itemId赋值为tempItemId
  selectedItemBoms.value.forEach(item => {
    item.itemId = tempItemId.value
  })
  console.log("提交数据: ", tempItemId.value)
  itemRequest.addItemToBom(selectedItemBoms.value, (data) => {
    console.log("添加结果: ", data)
    if (data.msg == "OK"){
      ElMessage({
        type: "success",
        message: "添加成功"
      });
      // 重新加载数据
      fetchItemList(searchItem);
    }
  })
}

//添加bom组按钮
function itemBomInsert(){
  dialogSelectVisiable.value = true;
}

function deleteDevList(){
  ElMessageBox.confirm('确定要删除选中的物料吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 用户点击了确定按钮，执行删除操作
    itemRequest.deleteItems(selectedItems.value, (data) => {
      if (data.msg == "OK"){
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        // 重新加载数据
        fetchItemList(searchItem);
      }
    })
  })
}

function handleDelete(row){
  ElMessageBox.confirm('确定要删除该物料吗？', '删除提醒', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    //点击确认后,将itemStatus的值设置为99
    row.itemStatus = 99;
    itemRequest.EditDateSubmit(row, (data) => {
      if (data.msg == "OK"){
        ElMessage({
          type: "success",
          message: "删除成功"
        })
        fetchItemList(searchItem);
      }
    })
  })
}

function handleEdit(row){


  //保存一个暂存的itemId
  tempItemId.value = row.itemId;
  //bom列表
  itemRequest.loadItemBomList(row.itemId,res=>{
    itemBomList.value = res.data
  })
  unitRequest.loadUnitList(searchUnit, function (data) {
    unitList.value = data.data.map(unit => ({
      unitId: unit.unitId,
      unitName: unit.unitName,
      unitOfMeasure: unit.unitCode
    }));
  });
  itemTypeRequest.loadItemTypeList(searchItemType,(data) => {
    itemTypeList.value = data.data.map(itemType => ({
      itemTypeId: itemType.itemTypeId,
      itemTypeName: itemType.itemTypeName,
      itemTypeCode: itemType.itemTypeCode,
      itemOrProduct: itemType.itemOrProduct
    }));
  });
  console.log("修改物料", row.itemId);
  itemRequest.loadUpdateInfo(row.itemId,res=>{
    updateFormData.value = res.data
    dialogUpdateVisiable.value = true // 显示弹窗
    console.log(updateFormData.value)
  })
}

//点击详情后的处理
function itemDetails(row) {
  itemRequest.loadUpdateInfo(row.itemId,res=>{
    updateFormData.value = res.data
    dialogDetailVisiable.value = true
  });
  itemRequest.loadItemBomList(row.itemId,res=>{
    itemBomList.value = res.data
  })
  itemRequest.querySipByItemId(row.itemId,res=>{
    itemSipList.value = res.data
  })
  itemRequest.querySopByItemId(row.itemId,res=>{
    itemSopList.value = res.data
  })
}

// 处理表格行选择事件
function handleSelectionChange(val) {
  selectedItems.value = val;
}

function insert(){
  dialogInsertVisiable.value = true
  unitRequest.loadUnitList(searchUnit, function (data) {
    unitList.value = data.data.map(unit => ({
      unitId: unit.unitId,
      unitName: unit.unitName,
      unitOfMeasure: unit.unitCode
    }));
  });
  itemTypeRequest.loadItemTypeList(searchItemType,(data) => {
    itemTypeList.value = data.data.map(itemType => ({
      itemTypeId: itemType.itemTypeId,
      itemTypeName: itemType.itemTypeName,
      itemTypeCode: itemType.itemTypeCode,
      itemOrProduct: itemType.itemOrProduct
    }));
  });
  console.log(itemTypeList)
  console.log(unitList)
}
function handleUpdataConfirm(){

  itemRequest.EditDateSubmit(updateFormData.value, res => {
    if (res.msg === "OK") {
      dialogUpdateVisiable.value = false;
      fetchItemList(searchItem.value);
      //关闭弹窗
      ElMessage({
        type: "success",
        message: "修改成功"
      })
    } else {
      console.log(res.msg);
    }
  })
}

function handleConfirm(){

  //将unitOfMeasure传入item
  formData.value.unitOfMeasure = unitList.value.find(unit => unit.unitName === formData.value.unitName).unitOfMeasure;
  //itemTypeId赋值
  formData.value.itemTypeId = itemTypeList.value.find(itemType => itemType.itemTypeName === formData.value.itemTypeName).itemTypeId;
  formData.value.itemTypeCode = itemTypeList.value.find(itemType => itemType.itemTypeName === formData.value.itemTypeName).itemTypeCode;
  formData.value.itemOrProduct = itemTypeList.value.find(itemType => itemType.itemTypeName === formData.value.itemTypeName).itemOrProduct;
  itemRequest.addItem(formData.value, (data) => {
    if (data.code === 200) {
      dialogInsertVisiable.value = false;
      fetchItemList(searchItem.value);
    } else {
      console.log(data.msg);
    }
  });
}
// 初始化获取数据
fetchItemList(searchItem.value);


onMounted(() => {
  fetchItemList(searchItem.value);  // 页面加载时获取数据

});
</script>

<style>
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 6px;
  cursor: pointer;
}
</style>
